package com.ldk.admin.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ldk.admin.constants.CONFIG;
import com.ldk.admin.constants.SESSION;
import com.ldk.base.framework.util.DateUtil;
import com.ldk.framework.entity.AdminUser;
import com.ldk.framework.entity.Companypermit;
import com.ldk.framework.entity.DriverBindCar;
import com.ldk.framework.entity.Driverapp;
import com.ldk.framework.entity.Drivereducate;
import com.ldk.framework.entity.Driverstat;
import com.ldk.framework.entity.PlatformDriver;
import com.ldk.framework.entity.RatedDriver;
import com.ldk.framework.entity.Vehicle;
import com.ldk.framework.entity.Vehicleinsurance;
import com.ldk.framework.entity.Vehicletotalmile;
import com.ldk.framework.enums.DriverCheckStatus;

import org.apache.commons.lang.StringUtils;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ldk.admin.common.LigerUIGridResult;
import com.ldk.admin.common.ResponseResult;
import com.ldk.admin.constants.FORM;
import com.ldk.admin.constants.ViewMode;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.base.framework.util.EncryptUtil;
import com.ldk.base.framework.util.OpenIdUtil;
import com.ldk.base.framework.util.RegexUtil;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.entity.Driver;
import com.ldk.framework.entity.ServiceConfig;
import com.ldk.framework.enums.DriverStatus;
import com.ldk.framework.enums.ServiceCode;
import com.ldk.framework.service.ICompanypermitService;
import com.ldk.framework.service.IDriverService;
import com.ldk.framework.service.IDriverappService;
import com.ldk.framework.service.IDrivereducateService;
import com.ldk.framework.service.IDriverstatService;
import com.ldk.framework.service.IPlatformDriverService;
import com.ldk.framework.service.IRatedDriverService;
import com.ldk.framework.service.IServiceConfigService;
import com.ldk.framework.service.IVehicleService;
import com.ldk.framework.service.IVehicleinsuranceService;
import com.ldk.framework.service.IVehicletotalmileService;

import static com.ldk.base.framework.util.SystemUtil.generateRandom;
import static com.ldk.base.framework.util.SystemUtil.generateSalt;

@Controller
@RequestMapping("/driver")
public class DriverController extends BaseController {
    /**
     * 路由地址
     */
    private final String route = "driver";
    /**
     * 模块名称
     */
    private final String module = "司机";

    @Autowired
    private IDriverService driverService;
    @Autowired
    private IVehicleService vehicleService;
    @Autowired
    private IVehicleinsuranceService vehicleinsuranceService;
    @Autowired
    private IVehicletotalmileService vehicletotalmileService;
    @Autowired
    private IServiceConfigService serviceConfigService;
    @Autowired
    private ICompanypermitService companypermitService;
    @Autowired
    private IPlatformDriverService platformDriverService;
    @Autowired
    private IDrivereducateService drivereducateService;
    @Autowired
    private IDriverappService driverappService;
    @Autowired
    private IDriverstatService driverstatService;
    @Autowired
    private IRatedDriverService ratedDriverService;

    @RequestMapping("/list")
    //public ModelAndView list(ModelMap map){
    public ModelAndView list(ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        if (this.getRoleId(request) == 6) {
            setLinks(map, "", "", module + "管理", "/" + route + "/list", "", "");
        } else {
            setLinks(map, "", "", module + "管理", "/" + route + "/list", "添加" + module, "/" + route + "/add");
        }
        map.addAttribute("route", route);
        map.addAttribute("module", module);
        map.addAttribute("companyList", getCompanyList());
        map.addAttribute("serviceCodeList", getServiceConfigList());
        //操作日志
        //this.insertOplog(request,module+"管理","","","查看",this.getAdminUserName(request).toString(), Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());
        String areaName = this.getAdminAreaName(request);
        map.addAttribute("areaName", areaName);

        if (this.getRoleId(request) == 6) {
            return new ModelAndView("/driver/list_sj");
        } else {
            return new ModelAndView("/driver/list");
        }
    }

    @RequestMapping("/list1")
    //public ModelAndView list(ModelMap map){
    public ModelAndView list1(ModelMap map, HttpServletRequest request,
                              HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        setLinks(map, "", "", "司机待审核列表", "/" + route + "/list1", "", "");
        map.addAttribute("route", route);
        map.addAttribute("module", module);

        //操作日志
        String areaName = this.getAdminAreaName(request);
        map.addAttribute("areaName", areaName);

        return new ModelAndView("/driver/list1");
    }

    @RequestMapping("/list2")
    public ModelAndView list2(ModelMap map, HttpServletRequest request,
                              HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        setLinks(map, "", "", "司机审核未通过列表", "/" + route + "/list2", "", "");
        map.addAttribute("route", route);
        map.addAttribute("module", module);

        //操作日志
        String areaName = this.getAdminAreaName(request);
        map.addAttribute("areaName", areaName);

        return new ModelAndView("/driver/list2");
    }

    @ResponseBody
    @RequestMapping("/getList")
    public LigerUIGridResult<Driver> getList(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                             @RequestParam(value = "pagesize", required = false, defaultValue = "10") int pageSize,
                                             @RequestParam(value = "startTime", required = false, defaultValue = "") String startTime,
                                             @RequestParam(value = "endTime", required = false, defaultValue = "") String endTime,
                                             @RequestParam(value = "serviceCode", required = false, defaultValue = "") String serviceCode,
                                             @RequestParam(value = "companyId", required = false, defaultValue = "") String companyId,
                                             @RequestParam(value = "searchKey", required = false, defaultValue = "") String searchKey,
                                             HttpServletRequest request) {
        int limit = pageSize;
        int offset = (page - 1) * pageSize;

        Driver query = new Driver();
        query.setCheckState(DriverCheckStatus.CheckSusses.getValue());
        if (!StringUtils.isBlank(searchKey)) {
            query.setSearchKey(searchKey);
        }
        if (!StringUtils.isBlank(companyId)) {
            query.setCompanyId(companyId);
        }
        AdminUser admin = (AdminUser) request.getSession().getAttribute(SESSION.USER);
        if (admin != null && admin.getRoleId() == CONFIG.COMPANY_ROLEID) {
            query.setCompanyId(admin.getCompanyId());
        }

        if (!StringUtils.isEmpty(startTime)) {
            long st = SystemUtil.stringToSeconds(startTime, "yyyy-MM-dd");
            query.setStartTime(st);
        }
        if (!StringUtils.isEmpty(endTime)) {
            long et = SystemUtil.stringToSeconds(endTime, "yyyy-MM-dd");
            et += 24 * 60 * 60;
            query.setEndTime(et);
        }
        if (!StringUtils.isBlank(serviceCode)) {
            query.setServiceCodes(serviceCode);
        }
        /*String areaName = this.getAdminAreaName(request);
        if (areaName != null && areaName != "") {
            query.setSearchKey(areaName);
        }*/
        CustomPageable pageable = new CustomPageable(offset, limit);

        Page<Driver> result = driverService.selectPageList("", query, pageable);

        LigerUIGridResult<Driver> grid = new LigerUIGridResult<>();
        grid.Total = result.getTotalElements();
        grid.Rows = result.getContent();

        // 生成6位固定ID号
        /*
        List<Driver>  list = driverService.selectAll("");
		for(int i=0;i<list.size();i++) {
			long dCommonId = driverService.generateDCommonId();

			Driver entity = new Driver();
			entity.setDriverId(list.get(i).getDriverId());
			entity.setdCommonId(dCommonId);

			int row = driverService.updateByKey("", entity);
		}
        */

        return grid;
    }

    @ResponseBody
    @RequestMapping("/getList1")
    public LigerUIGridResult<Driver> getList1(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                              @RequestParam(value = "pagesize", required = false, defaultValue = "10") int pageSize,
                                              @RequestParam(value = "searchKey", required = false, defaultValue = "") String searchKey,
                                              HttpServletRequest request) {
        int limit = pageSize;
        int offset = (page - 1) * pageSize;

        Driver query = new Driver();
        //待审核
        query.setCheckState(DriverCheckStatus.WaitCheck.getValue());
        if (searchKey != null && searchKey != "") {
            query.setSearchKey(searchKey);
        }
        AdminUser admin = (AdminUser) request.getSession().getAttribute(SESSION.USER);
        if (admin != null && admin.getRoleId() == CONFIG.COMPANY_ROLEID) {
            query.setCompanyId(admin.getCompanyId());
        }
        CustomPageable pageable = new CustomPageable(offset, limit);

        Page<Driver> result = driverService.selectPageList("", query, pageable);
        LigerUIGridResult<Driver> grid = new LigerUIGridResult<>();
        grid.Total = result.getTotalElements();
        grid.Rows = result.getContent();

        return grid;
    }

    @ResponseBody
    @RequestMapping("/getList2")
    public LigerUIGridResult<Driver> getList2(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                              @RequestParam(value = "pagesize", required = false, defaultValue = "10") int pageSize,
                                              @RequestParam(value = "searchKey", required = false, defaultValue = "") String searchKey,
                                              HttpServletRequest request) {
        int limit = pageSize;
        int offset = (page - 1) * pageSize;

        Driver query = new Driver();
        //待审核
        query.setCheckState(DriverCheckStatus.CheckFail.getValue());
        if (searchKey != null && searchKey != "") {
            query.setSearchKey(searchKey);
        }
        AdminUser admin = (AdminUser) request.getSession().getAttribute(SESSION.USER);
        if (admin != null && admin.getRoleId() == CONFIG.COMPANY_ROLEID) {
            query.setCompanyId(admin.getCompanyId());
        }

        CustomPageable pageable = new CustomPageable(offset, limit);

        Page<Driver> result = driverService.selectPageList("", query, pageable);
        LigerUIGridResult<Driver> grid = new LigerUIGridResult<>();
        grid.Total = result.getTotalElements();
        grid.Rows = result.getContent();

        return grid;
    }

    @RequestMapping("/add")
    public ModelAndView add(ModelMap map, HttpServletRequest request,
                            HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);

        setLinks(map, module + "管理", "/" + route + "/list", "添加" + module, "/" + route + "/add", "", "");
        setForm(map, "/" + route + "/insert", null);
        map.addAttribute("module", module);
        map.addAttribute("carRankList", getDictdataList(2));//2为车等级数据字典ID
        map.addAttribute("carSeatsList", getDictdataList(4));//4为车座位数据典ID
        map.addAttribute("bankNameList", getDictdataList(6));//6为银行名称数据字典ID
        map.addAttribute("serviceList", getServiceList());

        map.addAttribute("companyList", getCompanyList());

        Driver model = new Driver();

        return new ModelAndView("/driver/info", "model", model);
    }

    @RequestMapping("/check/{id}")
    public ModelAndView check(@PathVariable long id, ModelMap map, HttpServletRequest request,
                              HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        Driver query = new Driver();
        query.setDriverId(id);

        Driver model = driverService.selectByKey("", query);
        if (model == null) {
            return new ModelAndView("redirect:/" + route + "/list1");
        }
        setLinks(map, "司机待审核列表", "/" + route + "/list1", "审核" + module, "/" + route + "/check/" + id, "", "");
        setForm(map, "/" + route + "/check", null);
        map.addAttribute("module", module);
        map.addAttribute("carRankList", getDictdataList(2));//2为车等级数据字典ID
        map.addAttribute("carSeatsList", getDictdataList(4));//4为车座位数据典ID
        map.addAttribute("bankNameList", getDictdataList(6));//6为银行名称数据字典ID
        map.addAttribute("serviceList", getServiceList());
        map.addAttribute("companyList", getCompanyList());
        setViewMode(map, ViewMode.Edit);

        return new ModelAndView("/driver/checkinfo", "model", model);
    }

    @RequestMapping("/edit/{id}")
    public ModelAndView edit(@PathVariable long id, ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        Driver query = new Driver();
        query.setDriverId(id);

        Driver model = driverService.selectByKey("", query);
        if (model == null) {
            return new ModelAndView("redirect:/" + route + "/list");
        }
        setLinks(map, module + "管理", "/" + route + "/list", "编辑" + module, "/" + route + "/edit/" + id, "", "");
        setForm(map, "/" + route + "/update", null);
        map.addAttribute("module", module);
        map.addAttribute("carRankList", getDictdataList(2));//2为车等级数据字典ID
        map.addAttribute("carSeatsList", getDictdataList(4));//4为车座位数据典ID
        map.addAttribute("bankNameList", getDictdataList(6));//6为银行名称数据字典ID
        map.addAttribute("serviceList", getServiceList());
        map.addAttribute("companyList", getCompanyList());
        setViewMode(map, ViewMode.Edit);
        return new ModelAndView("/driver/info", "model", model);
    }

    @RequestMapping("/insert")
    public ModelAndView insert(@ModelAttribute("model") Driver model,
                               RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
                               HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        ResponseResult rst = new ResponseResult();
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
        if (StringUtils.isBlank(model.getPhoneNo())) {
            rst.AddError("手机号不能为空");
            return new ModelAndView("redirect:/" + route + "/add");
        }
        if (!RegexUtil.isPhoneNo(model.getPhoneNo())) {
            rst.AddError("请输入有效手机号");
            return new ModelAndView("redirect:/" + route + "/add");
        }
        if (StringUtils.isBlank(model.getIdCard())) {
            rst.AddError("身份证不能为空");
            return new ModelAndView("redirect:/" + route + "/add");
        }
        if (!RegexUtil.isIdCard(model.getIdCard())) {
            rst.AddError("请输入有效身份证");
            return new ModelAndView("redirect:/" + route + "/add");
        }
        try {
            //手机号做为司机的唯一编号
            Driver query = new Driver();
            query.setPhoneNo(model.getPhoneNo());

            Driver existObj = driverService.selectOne("", query);
            if (existObj != null) {
                rst.AddError("司机已经存在");
                return new ModelAndView("redirect:/" + route + "/add");
            }
            if (model.getEnabled() == null) {
                model.setEnabled(false);
            }
            if (model.getStatus() == null) {
                model.setStatus(DriverStatus.OffLine.getValue());
            }
            String slat = generateSalt(6);
            int len = model.getIdCard().length();
            String rawPwd = model.getIdCard().substring(len - 6);
            String pwd = EncryptUtil.md5(rawPwd + slat);
            model.setPwd(pwd);
            model.setSlat(slat);
            //生成openId
            String openId = OpenIdUtil.encrypt(model.getPhoneNo() + model.getIdCard(), SystemUtil.getAllSeconds(), slat);
            model.setOpenId(openId);
            model.setOperateTime(SystemUtil.getAllSeconds());
            model.setOperator(getAdminTrueName(request));
            model.setStar(3.0);
            //默认参数
            model.setCarSeats(0);
            model.setBalance(0.0);
            model.setLon(0.0);
            model.setLat(0.0);
            model.setIncome(0.0);
            model.setCash(0.0);
            model.setOrderCount(0);
            model.setCancelTripTimes(0);
            model.setDisableDays(0);
            model.setDisableDate(0L);
            model.setCheckState(DriverCheckStatus.CheckSusses.getValue());
            model.setBindCar(true);
            model.setSourceType(0);
            model.setScore(100.0);
            model.setAreaCode("520100");

            if (!TextUtils.isEmpty(model.getServiceCodes())) {
                String serviceNames = "";
                String[] list = model.getServiceCodes().split(",");
                if (list != null && list.length > 0) {
                    for (int i = 0; i < list.length; i++) {
                        String serviceCode = list[i];
                        if (serviceCode.equals(ServiceCode.KC.getCode())) {
                            serviceNames = serviceNames + ServiceCode.KC.getName();
                        } else if (serviceCode.equals(ServiceCode.ZC.getCode())) {
                            serviceNames = serviceNames + ServiceCode.ZC.getName();
                        } else if (serviceCode.equals(ServiceCode.CJT.getCode())) {
                            serviceNames = serviceNames + ServiceCode.CJT.getName();
                        }
                        if (i < list.length - 1) {
                            serviceNames = serviceNames + ",";
                        }
                    }
                }
                model.setServiceNames(serviceNames);
            }
            int row = driverService.insert("", model);
            if (row > 0) {
                //后台添加司机成功后，默认为审核通过，插入车辆信息表中

                //如车辆已存在，则不需要插入
                Vehicle queryv = new Vehicle();
                queryv.setVehicleNo(model.getCarNo());
                queryv.setEnabled(true);
                Vehicle vehicle = vehicleService.selectOne("", queryv);
                if (vehicle == null) {
                   /*vehicle = new Vehicle();
                     vehicle.setDriverPhone(model.getPhoneNo());
                     vehicle.setCompanyId(model.getCompanyId());
                     vehicle.setCompanyName(model.getCompanyName());
                     vehicle.setVehicleNo(model.getCarNo());
                     vehicle.setBrand(model.getCarBrand());
                     vehicle.setModel(model.getCarRank());
                     vehicle.setVehicleType(model.getCarType());
                     vehicle.setVehicleColor(model.getCarColor());
                     vehicle.setSeats(Long.parseLong(model.getCarSeats() + ""));
                     vehicle.setDatetime(SystemUtil.getAllSeconds());
                     vehicle.setEnabled(true);
                     vehicle.setDriverOpenId(openId);
                     vehicleService.insert("", vehicle);
                    */
                    saveDat(model);
                }
                //操作日志
                this.insertOplog(request, module, "", "", "添加:" + model.getTrueName(), this.getAdminUserName(request).toString(),
                        Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

                rst.AddOk("添加" + module + "成功");
            } else {
                rst.AddError("添加" + module + "失败");
            }
        } catch (Exception e) {
            rst.AddError("添加" + module + "失败");
            logger.error(e.getMessage());
        }
        return new ModelAndView("redirect:/" + route + "/add");
    }

    @RequestMapping("/update")
    public ModelAndView update(@ModelAttribute("model") Driver model,
                               RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
                               HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        ResponseResult rst = new ResponseResult();

        redAttr.addAttribute("id", model.getDriverId());
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);

        try {
            //手机号做为司机的唯一编号
            Driver query = new Driver();
            query.setPhoneNo(model.getPhoneNo());

            Driver config = driverService.selectOne("", query);
            if (config != null && !config.getDriverId().equals(model.getDriverId())) {
                rst.AddError("司机已存在");
                return new ModelAndView("redirect:/" + route + "/edit/{id}");
            }
            if (model.getEnabled() == null) {
                model.setEnabled(false);
            }
            if (!TextUtils.isEmpty(model.getServiceCodes())) {
                String serviceNames = "";
                String[] list = model.getServiceCodes().split(",");
                if (list != null && list.length > 0) {
                    for (int i = 0; i < list.length; i++) {
                        String serviceCode = list[i];
                        if (serviceCode.equals(ServiceCode.KC.getCode())) {
                            serviceNames = serviceNames + ServiceCode.KC.getName();
                        } else if (serviceCode.equals(ServiceCode.ZC.getCode())) {
                            serviceNames = serviceNames + ServiceCode.ZC.getName();
                        } else if (serviceCode.equals(ServiceCode.CJT.getCode())) {
                            serviceNames = serviceNames + ServiceCode.CJT.getName();
                        }
                        if (i < list.length - 1) {
                            serviceNames = serviceNames + ",";
                        }
                    }
                }
                model.setServiceNames(serviceNames);
            }

            model.setOperateTime(SystemUtil.getAllSeconds());
            model.setOperator(getAdminTrueName(request));
            //操作日志
            this.insertOplog(request, module, "", "", "修改:" + model.getTrueName(), this.getAdminUserName(request).toString(),
                    Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());
            int row = driverService.updateByKey("", model);
            if (row > 0) {
                rst.AddOk("修改" + module + "成功");
            } else {
                rst.AddError("修改" + module + "失败");
            }
        } catch (Exception e) {
            rst.AddError("修改" + module + "失败");
            logger.error(e.getMessage());
        }

        return new ModelAndView("redirect:/" + route + "/edit/{id}");
    }

    @RequestMapping("/check")
    public ModelAndView check(@ModelAttribute("model") Driver model,
                              RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
                              HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        ResponseResult rst = new ResponseResult();

        redAttr.addAttribute("id", model.getDriverId());
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);

        try {
            //手机号做为司机的唯一编号
            Driver query = new Driver();
            query.setPhoneNo(model.getPhoneNo());

            Driver config = driverService.selectOne("", query);
            if (config != null && !config.getDriverId().equals(model.getDriverId())) {
                rst.AddError("司机已存在");
                return new ModelAndView("redirect:/" + route + "/edit/{id}");
            }
            if (model.getEnabled() == null) {
                model.setEnabled(false);
            }
            if (!TextUtils.isEmpty(model.getServiceCodes())) {
                String serviceNames = "";
                String[] list = model.getServiceCodes().split(",");
                if (list != null && list.length > 0) {
                    for (int i = 0; i < list.length; i++) {
                        String serviceCode = list[i];
                        if (serviceCode.equals(ServiceCode.KC.getCode())) {
                            serviceNames = serviceNames + ServiceCode.KC.getName();
                        } else if (serviceCode.equals(ServiceCode.ZC.getCode())) {
                            serviceNames = serviceNames + ServiceCode.ZC.getName();
                        } else if (serviceCode.equals(ServiceCode.CJT.getCode())) {
                            serviceNames = serviceNames + ServiceCode.CJT.getName();
                        }
                        if (i < list.length - 1) {
                            serviceNames = serviceNames + ",";
                        }
                    }
                }
                model.setServiceNames(serviceNames);
            }
            model.setOperateTime(SystemUtil.getAllSeconds());
            model.setOperator(getAdminTrueName(request));
            //操作日志
            this.insertOplog(request, module, "", "", "修改:" + model.getTrueName(), this.getAdminUserName(request).toString(),
                    Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());
            int row = driverService.updateByKey("", model);
            if (row > 0) {
                rst.AddOk("修改" + module + "成功");
                //审核司机成功后，插入车辆信息表中
                saveDat(model);
            } else {
                rst.AddError("修改" + module + "失败");
            }
        } catch (Exception e) {
            rst.AddError("修改" + module + "失败");
            logger.error(e.getMessage());
        }

        return new ModelAndView("redirect:/" + route + "/edit/{id}");
    }


    private void saveDat(Driver model) {
        String companyId = "5201HDCX8779";
        Vehicle vehicle = new Vehicle();
        Date date = DateUtil.AddMonth(new Date(), -generateRandom(20));
        try {
            vehicle.setCompanyId(companyId);
            vehicle.setAddress(model.getAreaCode());
            vehicle.setDriverPhone(model.getPhoneNo());
            vehicle.setCompanyId(model.getCompanyId());
            vehicle.setCompanyName(model.getCompanyName());
            vehicle.setVehicleNo(model.getCarNo());
            vehicle.setBrand(model.getCarBrand());
            vehicle.setModel(model.getCarBrand() + generateSalt(6));
            vehicle.setVehicleType(model.getCarType());
            vehicle.setVehicleColor(model.getCarColor());
            vehicle.setSeats(Long.parseLong(model.getCarSeats() + ""));
            vehicle.setDatetime(SystemUtil.getAllSeconds());
            vehicle.setEnabled(true);
            vehicle.setDriverOpenId(model.getOpenId());

            vehicle.setPlateColor("1");
            vehicle.setOwnerName(model.getTrueName());
            vehicle.setEngineId(generateRandom(50) + "QYJ" + generateRandom(20) + "K" + generateRandom(9));
            vehicle.setVIN("LSKGC" + generateRandom(9) + "GC" + generateRandom(20) + "KA" + generateRandom(99999));
            vehicle.setCertifyDateA(DateUtil.DatetoString(DateUtil.AddMonth(new Date(), -generateRandom(20)), DateUtil.dbyyyymmdd1));
            vehicle.setFuelType("1");
            vehicle.setEngineDisplace("2.0");
            vehicle.setTransAgency("贵阳市交通委员会");
            vehicle.setTransArea("贵阳市");
            Date date1 = DateUtil.AddMonth(new Date(), generateRandom(20));
            Date date2 = DateUtil.AddMonth(new Date(), -generateRandom(20));
            vehicle.setTransDateStart(DateUtil.DatetoString(date, DateUtil.dbyyyymmdd1));
            vehicle.setTransDateStop(DateUtil.DatetoString(date1, DateUtil.dbyyyymmdd1));
            vehicle.setCertifyDateB(DateUtil.DatetoString(date2, DateUtil.dbyyyymmdd1));
            vehicle.setFixState("1");
            vehicle.setCheckState("1");
            vehicle.setFeePrintId("00000000");
            vehicle.setGPSBrand("全球通");
            vehicle.setGPSModel("W1");
            vehicle.setGPSIMEI("14425635244");
            Date date4 = DateUtil.AddDay(date, 3 * generateRandom(20));
            vehicle.setGPSInstallDate(DateUtil.DatetoString(date4, DateUtil.dbyyyymmdd1));
            Date date3 = DateUtil.AddMonth(date, generateRandom(5));
            vehicle.setRegisterDate(DateUtil.DatetoString(date3, DateUtil.dbyyyymmdd1));
            vehicle.setCommercialType(1L);
            vehicle.setFareType("HDCX002");
            vehicle.setState(0L);
            vehicle.setFlag(1L);
            vehicle.setUpdateTime(DateUtil.DatetoString(new Date(), DateUtil.dbyyyymmdd1));
            vehicle.setUploadFlag(1);
            vehicleService.insert("", vehicle);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //插入车辆保险
        try {
            Vehicleinsurance vehicleinsurance = new Vehicleinsurance();
            vehicleinsurance.setCompanyId(companyId);
            vehicleinsurance.setVehicleNo(vehicle.getVehicleNo());
            vehicleinsurance.setInsurCom("中国平安财产保险股份有限公司(贵阳中心支公司)");
            vehicleinsurance.setInsurNum(generateSalt(6) + generateSalt(6) + generateSalt(6));
            vehicleinsurance.setInsurType("机动车交通事故责任强制保险");
            vehicleinsurance.setInsurCount(1500000.00);
            Date date5 = DateUtil.AddDay(date, 3 * generateRandom(99));
            Date date6 = DateUtil.AddYear(date5, 1);
            vehicleinsurance.setInsurEff(Long.parseLong(DateUtil.DatetoString(date5, DateUtil.dbyyyymmdd1)));
            vehicleinsurance.setInsurExp(Long.parseLong(DateUtil.DatetoString(date6, DateUtil.dbyyyymmdd1)));
            vehicleinsurance.setFlag(1L);
            vehicleinsurance.setUpdateTime(Long.parseLong(DateUtil.DatetoString(new Date(), DateUtil.dbyyyymmdd1)));
            vehicleinsurance.setUpdateTime2(0L);
            vehicleinsuranceService.insertUpper("", vehicleinsurance);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //插入车辆里程
        try {
            Vehicletotalmile vehicletotalmile = new Vehicletotalmile();
            vehicletotalmile.setCompanyId(companyId);
            if (!TextUtils.isEmpty(model.getAreaCode())) {
                vehicletotalmile.setAddress(Long.parseLong(model.getAreaCode()));
            } else {
                vehicletotalmile.setAddress(0L);
            }
            vehicletotalmile.setVehicleNo(vehicle.getVehicleNo());
            vehicletotalmile.setTotalMile(100.0 * generateRandom(9) * generateRandom(9) * generateRandom(9));
            vehicletotalmile.setFlag(1L);
            vehicletotalmile.setUpdateTime(Long.parseLong(DateUtil.DatetoString(new Date(), DateUtil.dbyyyymmdd1)));
            vehicletotalmile.setUpdateTime2(0L);
            vehicletotalmileService.insertUpper("", vehicletotalmile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //插入司机信息
        Date date9 = new Date();
        try {
            PlatformDriver platformDriver = new PlatformDriver();
            platformDriver.setCompanyId(companyId);
            platformDriver.setAddress(model.getAreaCode());
            platformDriver.setDriverName(model.getTrueName());
            platformDriver.setDriverPhone(model.getPhoneNo());
            if (model.getSex() != null && model.getSex().equals("女")) {
                platformDriver.setDriverGender("2");
            } else {
                platformDriver.setDriverGender("1");
            }
            String birth = DateUtil.getBirthFromIdCard(model.getIdCard());
            if (TextUtils.isEmpty(birth)) {
                birth = "19870521";
            }
            platformDriver.setDriverBirthday(birth);
            platformDriver.setDriverNationality("中国");
            platformDriver.setDriverNation("汉族");
            platformDriver.setDriverContactAddress("贵阳市");
            platformDriver.setLicenseId(model.getIdCard());
            Date date7 = DateUtil.AddMonth(new Date(), -24 - generateRandom(30));
            platformDriver.setGetDriverLicenseDate(DateUtil.DatetoString(date7, DateUtil.dbyyyymmdd1));
            platformDriver.setDriverLicenseOn(DateUtil.DatetoString(date7, DateUtil.dbyyyymmdd1));
            platformDriver.setDriverLicenseOff(DateUtil.DatetoString(DateUtil.AddYear(date7, 10), DateUtil.dbyyyymmdd1));
            platformDriver.setTaxiDriver(0L);
            platformDriver.setCertificateNo(generateSalt(6) + generateSalt(6));
            platformDriver.setNetworkCarIssueOrganization("贵阳市交通运输局");
            Date date8 = DateUtil.AddDay(new Date(), -generateRandom(20) * 30);
            platformDriver.setNetworkCarIssueDate(DateUtil.DatetoString(date8, DateUtil.dbyyyymmdd1));
            platformDriver.setGetNetworkCarProofDate(DateUtil.DatetoString(date8, DateUtil.dbyyyymmdd1));
            platformDriver.setNetworkCarProofOn(DateUtil.DatetoString(date8, DateUtil.dbyyyymmdd1));
            platformDriver.setNetworkCarProofOff(DateUtil.DatetoString(DateUtil.AddYear(date8, 3), DateUtil.dbyyyymmdd1));
            platformDriver.setRegisterDate(DateUtil.DatetoString(DateUtil.AddDay(date8, generateRandom(50)), DateUtil.dbyyyymmdd1));
            platformDriver.setFullTimeDriver(0L);
            platformDriver.setInDriverBlacklist(0L);
            platformDriver.setCommercialType(1L);
            platformDriver.setContractCompany("贵州金汇达导航科技有限公司");
            date9 = DateUtil.AddDay(new Date(), -generateRandom(100) * 30);
            platformDriver.setContractOn(DateUtil.DatetoString(date9, DateUtil.dbyyyymmdd1));
            platformDriver.setContractOff(DateUtil.DatetoString(DateUtil.AddYear(date9, 2), DateUtil.dbyyyymmdd1));
            platformDriver.setState(0L);
            platformDriver.setFlag(1L);
            platformDriver.setEnabled(false);
            platformDriver.setUpdateTime(DateUtil.DatetoString(new Date(), DateUtil.dbyyyymmdd1));
            platformDriverService.insert("", platformDriver);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //网约车驾驶员培训信息
        try {
            Drivereducate drivereducate = new Drivereducate();
            drivereducate.setCompanyId(companyId);
            if (!TextUtils.isEmpty(model.getAreaCode())) {
                drivereducate.setAddress(Long.parseLong(model.getAreaCode()));
            } else {
                drivereducate.setAddress(0L);
            }
            drivereducate.setLicenseId(model.getIdCard());
            drivereducate.setCourseName("网约车从业资格证");
            drivereducate.setCourseDate(Long.parseLong(DateUtil.DatetoString(DateUtil.AddDay(date9, 10), DateUtil.dbyyyymmdd1)));
            drivereducate.setStartTime1(Long.parseLong(DateUtil.DatetoString(DateUtil.AddDay(date9, 10), DateUtil.dbyyyymmdd1)));
            drivereducate.setStopTime(Long.parseLong(DateUtil.DatetoString(DateUtil.AddDay(date9, 12), DateUtil.dbyyyymmdd1)));
            drivereducate.setDuration(48.0);
            drivereducate.setFlag(1L);
            drivereducate.setUpdateTime(Long.parseLong(DateUtil.DatetoString(new Date(), DateUtil.dbyyyymmdd1)));
            drivereducate.setUpdateTime2(0L);
            drivereducateService.insertUpper("", drivereducate);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //驾驶员移动终端信息接口
        try {
            Driverapp driverapp = new Driverapp();
            driverapp.setCompanyId(companyId);
            if (!TextUtils.isEmpty(model.getAreaCode())) {
                driverapp.setAddress(Long.parseLong(model.getAreaCode()));
            } else {
                driverapp.setAddress(0L);
            }
            driverapp.setLicenseId(model.getIdCard());
            driverapp.setDriverPhone(model.getPhoneNo());
            driverapp.setNetType(generateRandom(2) * 1L);
            driverapp.setAppVersion("3.38");
            driverapp.setMapType(2L);
            driverapp.setState(0L);
            driverapp.setFlag(1L);
            driverapp.setUpdateTime(Long.parseLong(DateUtil.DatetoString(new Date(), DateUtil.dbyyyymmdd1)));
            driverapp.setUpdateTime2(0L);
            driverappService.insertUpper("", driverapp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //驾驶员移动终端信息接口
        try {
            Driverstat driverstat = new Driverstat();
            driverstat.setCompanyId(companyId);
            if (!TextUtils.isEmpty(model.getAreaCode())) {
                driverstat.setAddress(Long.parseLong(model.getAreaCode()));
            } else {
                driverstat.setAddress(0L);
            }
            driverstat.setLicenseId(model.getIdCard());
            driverstat.setCycle(Long.parseLong((DateUtil.DatetoString(new Date(), DateUtil.dbyyyymmdd1))));
            driverstat.setOrderCount(0L);
            driverstat.setTrafficViolationCount(0L);
            driverstat.setComplainedCount(0L);
            driverstat.setFlag(1L);
            driverstat.setUpdateTime(Long.parseLong(DateUtil.DatetoString(new Date(), DateUtil.dbyyyymmdd1)));
            driverstat.setUpdateTime2(0L);
            driverstatService.insertUpper("", driverstat);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //驾驶员信誉
        try {
            RatedDriver ratedDriver = new RatedDriver();
            ratedDriver.setCompanyId(companyId);
            ratedDriver.setLicenseId(model.getIdCard());
            ratedDriver.setLevel(5L);
            ratedDriver.setTestDate(Long.parseLong(DateUtil.DatetoString(new Date(), DateUtil.dbyyyymmdd1)));
            ratedDriver.setTestDepartment("贵州金汇达导航科技有限公司");
            ratedDriver.setTestDate2(0L);
            ratedDriverService.insertUpper("", ratedDriver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 浏览
     *
     * @param id
     * @param map
     * @return
     */
    @RequestMapping("/view/{id}")
    public ModelAndView view(@PathVariable long id, ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        setViewMode(map, ViewMode.View);
        Driver query = new Driver();
        query.setDriverId(id);
        Driver model = driverService.selectByKey("", query);

        map.addAttribute("module", module);
        map.addAttribute("carRankList", getDictdataList(2));

        return new ModelAndView("/driver/info", "model", model);
    }

    /**
     * 设置密码
     *
     * @param id
     * @param map
     * @return
     */
    @RequestMapping("/pwd/{id}")
    public ModelAndView pwd(@PathVariable long id, ModelMap map, HttpServletRequest request,
                            HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        setLinks(map, module + "管理", "/" + route + "/list", "修改密码", "/" + route + "/pwd/" + id, "", "");
        setForm(map, "/" + route + "/pwd/submit", null);
        map.addAttribute("module", module);

        Driver query = new Driver();
        query.setDriverId(id);

        Driver model = driverService.selectByKey("", query);

        return new ModelAndView("/driver/pwd", "model", model);
    }

    /**
     * 提交设置密码
     *
     * @param map
     * @return
     * @paramid
     */
    @RequestMapping("/pwd/submit")
    public ModelAndView pwdSubmit(@RequestParam(value = "driverId", required = true) long driverId,
                                  @RequestParam(value = "newPwd", required = true) String newPwd,
                                  @RequestParam(value = "surePwd", required = true) String surePwd,
                                  RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
                                  HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        ResponseResult rst = new ResponseResult();

        redAttr.addAttribute("id", driverId);
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
        Boolean success = false;
        try {
            if (StringUtils.isBlank(newPwd)) {
                rst.AddError("新密码不能为空");
                return new ModelAndView("redirect:user/pwd/{id}");
            }
            if (!newPwd.equals(surePwd)) {
                rst.AddError("输入密码不一致");
                return new ModelAndView("redirect:user/pwd/{id}");
            }
            String slat = generateSalt(6);
            String pwd = EncryptUtil.md5(newPwd + slat);

            Driver entity = new Driver();
            entity.setDriverId(driverId);
            entity.setPwd(pwd);
            entity.setSlat(slat);

            Driver driver = driverService.selectByKey("", entity);
            //操作日志
            this.insertOplog(request, module, "", "", "修改密码:" + driver.getTrueName(), this.getAdminUserName(request).toString(),
                    Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());
            int row = driverService.updateByKey("", entity);
            success = row > 0;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            rst.AddOk("修改密码成功");
        } else {
            rst.AddError("修改密码失败");
        }

        return new ModelAndView("redirect:/" + route + "/pwd/{id}");
    }


    /**
     * 绑定车辆
     *
     * @param id
     * @param map
     * @return
     */
    @RequestMapping("/bindcar/{id}")
    public ModelAndView bindcar(@PathVariable long id, ModelMap map, HttpServletRequest request,
                                HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        setLinks(map, module + "管理", "/" + route + "/list", "绑定车辆", "/" + route + "/bindcar/" + id, "", "");
        setForm(map, "/" + route + "/bindcar/submit", null);
        map.addAttribute("module", module);
        map.addAttribute("carList", getVehicleList());

        Driver query = new Driver();
        query.setDriverId(id);

        Driver model = driverService.selectByKey("", query);

        return new ModelAndView("/driver/bindcar", "model", model);
    }

    /**
     * 提交绑定车辆
     *
     * @param map
     * @return
     * @paramid
     */
    @RequestMapping("/bindcar/submit")
    public ModelAndView bindcarSubmit(@RequestParam(value = "driverId", required = true) long driverId,
                                      @RequestParam(value = "carNo", required = true) String carNo,
                                      RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
                                      HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        ResponseResult rst = new ResponseResult();

        redAttr.addAttribute("id", driverId);
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
        Boolean success = false;
        try {
            if (StringUtils.isBlank(carNo)) {
                rst.AddError("车牌号不能为空");
                return new ModelAndView("redirect:driver/bindcar/{id}");
            }

            //查询车辆信息
            Vehicle query = new Vehicle();
            query.setVehicleNo(carNo);
            query.setEnabled(true);
            Vehicle vehicle = vehicleService.selectOne("", query);
            if (vehicle == null) {
                rst.AddError("车牌号不存在");
                return new ModelAndView("redirect:driver/bindcar/{id}");
            }

            Driver entity = new Driver();
            entity.setDriverId(driverId);
            entity.setBindCar(true);
            entity.setCarNo(carNo);
            entity.setCarBrand(vehicle.getBrand());
            entity.setCarRank(vehicle.getModel());
            entity.setCarType(vehicle.getVehicleType());
            entity.setCarColor(vehicle.getVehicleColor());
            entity.setCarSeats(Integer.parseInt(vehicle.getSeats() + ""));
            Driver driver = driverService.selectByKey("", entity);
            //操作日志
            this.insertOplog(request, module, "", "", "绑定车辆:" + driver.getTrueName(), this.getAdminUserName(request).toString(),
                    Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());
            int row = driverService.updateByKey("", entity);
            success = row > 0;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            rst.AddOk("绑定车辆成功");
        } else {
            rst.AddError("绑定车辆失败");
        }
        return new ModelAndView("redirect:/" + route + "/bindcar/{id}");
    }

    //解绑车辆
    @ResponseBody
    @RequestMapping("/unbindCar/{id}")
    public ResponseResult unbindCar(@PathVariable long id, HttpServletRequest request) {

        ResponseResult rst = new ResponseResult();
        if (id < 1) {
            rst.AddError("删除" + module + "错误");
            return rst;
        }
        Boolean successed = false;
        try {
            Driver entity = new Driver();
            entity.setDriverId(id);
            entity.setBindCar(false);
            entity.setCarNo("");
            entity.setCarBrand("");
            entity.setCarRank("");
            entity.setCarType("");
            entity.setCarColor("");
            entity.setCarSeats(0);
            //Driver driver = driverService.selectByKey("", query);
            int row = driverService.updateByKey("", entity);
            //操作日志
            this.insertOplog(request, module, "", "", "解绑车辆id:" + id, this.getAdminUserName(request).toString(),
                    Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());
            successed = row > 0;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (successed) {
            rst.AddOk("解绑车辆成功");
        } else {
            rst.AddError("解绑车辆失败");
        }
        return rst;
    }

    @ResponseBody
    @RequestMapping("/remove/{id}")
    public ResponseResult remove(@PathVariable long id, HttpServletRequest request) {

        ResponseResult rst = new ResponseResult();
        if (id < 1) {
            rst.AddError("删除" + module + "错误");
            return rst;
        }
        Boolean successed = false;
        try {
            Driver query = new Driver();
            query.setDriverId(id);

            Driver driver = driverService.selectByKey("", query);
            //操作日志
            this.insertOplog(request, module, "", "", "删除:" + driver.getTrueName(), this.getAdminUserName(request).toString(),
                    Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

            int row = driverService.deleteByKey("", query);
            successed = row > 0;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (successed) {
            rst.AddOk("删除" + module + "成功");
        } else {
            rst.AddError("删除" + module + "失败");
        }

        return rst;
    }

    /**
     * 获取开通服务
     *
     * @return
     */
    private List<ServiceConfig> getServiceList() {
        ServiceConfig query = new ServiceConfig();
        query.setEnabled(true);

        return serviceConfigService.selectList("", query);
    }

    /**
     * 获取分公司列表
     *
     * @return
     */
    private List<Companypermit> getCompanyList() {
        Companypermit query = new Companypermit();
        query.setEnabled(true);

        return companypermitService.selectList("", query);
    }

    private List<ServiceConfig> getServiceConfigList() {
        return serviceConfigService.selectAll("");
    }

    /**
     * 车辆列表
     *
     * @return
     */
    private List<DriverBindCar> getVehicleList() {
        return driverService.findVehicleList("");
    }
}
